package com.atguigu.guli.service.sms.controller;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.aliyuncs.exceptions.ClientException;
import com.atguigu.commonutils.FormUtils;
import com.atguigu.commonutils.RandomUtils;
import com.atguigu.commonutils.ResultCodeEnum;
import com.atguigu.commonutils.result.R;
import com.atguigu.guli.service.base.Exception.GuliException;
import com.atguigu.guli.service.sms.service.SmsService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @author: Mr.Wang
 * @date: 2021-06-13 18:08
 * @description:
 */
@CrossOrigin
@Api(tags = "阿里云短信服务")
@Slf4j
@RestController
@RequestMapping("/api/sms")
public class ApiSmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/send/{mobile}")
    public R getCode(@PathVariable String mobile) throws ClientException {
        if (StringUtil.isEmpty(mobile) || !FormUtils.isMobile(mobile)) {
            log.error("请输入正确的手机号码 ");
            throw new GuliException(ResultCodeEnum.LOGIN_PHONE_ERROR);
        }

        //验证通过则调用短信服务发送验证码
           //生成验证码
        String code = RandomUtils.getSixBitRandom();
           //发送验证码
        smsService.send(mobile,code);

        System.out.println("code:"+code);

          // 将验证码存入redis中  5分钟有效
        redisTemplate.opsForValue().set(mobile,code,5, TimeUnit.MINUTES);

        return R.ok().message("短信发送成功");
    }
}
